package fy.erp.dao;

import com.seeyon.v3x.webmail.domain.MailInfo;
import fy.config.FyConfig;
import fy.util.DBUtil;
import fy.util.MyUtil;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class FYELingLiaoDao
{
    private static Log log = LogFactory.getLog(FYELingLiaoDao.class);
    private static String updateSQL = " update apps.FYG_6_INV_DELV_HEADER f set f.oa_status = ?,f.APPROVAL_DATE = to_date(?,'yyyy-MM-dd HH24:mi:ss') where f.req_num = ? and f.oa_status <> 'APPROVED'";
    private static String formTable;
    private static String column;
    private static String queryERPNumberSQL;

    private static void sendMail(String content)
    {
        MailInfo mi = new MailInfo();
        mi.setTo("erp@fuyaogroup.com");
        mi.setFrom("oasystem@fuyaogroup.com");
        mi.setSubject("Materialanforderungslist领料发料单异常");
        mi.setContentText(content);
        MyUtil.sendMail(mi);
    }

    public static boolean save(String erpNumber, short flowStatus)
    {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = df.format(day);
        Connection conn = null;
        PreparedStatement pst = null;
        boolean success = false;

        System.out.println("*****" + flowStatus + "*****" + 3 + "*************" + erpNumber);
        try
        {
            conn = DBUtil.connect(FyConfig.getERP_DB_CONFIG());





            pst = conn.prepareStatement(updateSQL);
            pst.setString(
                    1,




                    flowStatus == 6 ? "STOP" : flowStatus == 7 ? "PENDING" : flowStatus == 5 ? "RETURNED" : flowStatus == 1 ? "SUBMITTED" : flowStatus == 3 ? "APPROVED" :
                            "UNKNOWN");
            pst.setString(2, dateTime);
            pst.setString(3, erpNumber);

            pst.execute();

            conn.commit();

            success = true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.error(
                    "存储领料发料单状态异常，ERP单据号:" +
                            erpNumber, e);
            if ((flowStatus == 3) ||
                    (flowStatus == 6) ||
                    (flowStatus == 5)) {
                sendMail(


                        "更改领料发料单状态发生异常，ERP单据号：" + erpNumber + "，状态：" + (


                                flowStatus == 6 ? "STOP" : flowStatus == 5 ? "RETURNED" : flowStatus == 1 ? "SUBMITTED" : flowStatus == 3 ? "APPROVED" :
                                        "UNKNOWN"));
            }
        }
        finally
        {
            DBUtil.close(pst, conn);
        }
        return success;
    }

    public static String queryERPNumber(long summaryID)
    {
        String erpNumber = null;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try
        {
            conn = DBUtil.connect(FyConfig.getOA_DB_CONFIG());
            if ((formTable == null) || (column == null))
            {
                pst =
                        conn.prepareStatement("select a.datadefine from col_summary s,form_appmain a where s.form_appid = a.id and s.id = ?");

                pst.setLong(1, summaryID);

                rs = pst.executeQuery();
                if (rs.next())
                {
                    String datadefine = rs.getString(1);
                    parseDataDefine(datadefine);
                    queryERPNumberSQL =
                            " select f." +
                                    column +
                                    " from col_summary s ," +
                                    formTable +
                                    " f where s.id = ? and s.form_recordid = f.id";
                }
                DBUtil.close(rs, pst);
            }
            pst = conn.prepareStatement(queryERPNumberSQL);
            pst.setLong(1, summaryID);
            rs = pst.executeQuery();
            if (rs.next()) {
                erpNumber = rs.getString(1);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.error("表单撤销事件查询ＥＲＰ单据编号发生异常,单据号：" + summaryID, e);
        }
        finally
        {
            DBUtil.close(rs, pst, conn);
        }
        return erpNumber;
    }

    private static void parseDataDefine(String datadefine)
            throws Exception
    {
        Document doc = DocumentHelper.parseText(datadefine);

        Element root = doc.getRootElement();

        List nodes = root.selectNodes("//Define/DataDefine/TableList/Table");
        if (nodes != null) {
            for (Iterator iter = nodes.iterator(); iter.hasNext();)
            {
                Element node = (Element)iter.next();
                String name = node.attributeValue("name");
                if (name.indexOf("formmain") != -1) {
                    formTable = name;
                }
            }
        }
        nodes.clear();
        nodes = root
                .selectNodes("//Define/DataDefine/TableList/Table/FieldList/Field");
        if (nodes != null) {
            for (Iterator iter = nodes.iterator(); iter.hasNext();)
            {
                Element node = (Element)iter.next();
                String display = node.attributeValue("display");
                if (display.equals("ERP单据编号")) {
                    column = node.attributeValue("name");
                }
            }
        }
    }

    public static Connection connect(String driverClassName, String url, String userName, String password)
            throws Exception
    {
        Class.forName(driverClassName);
        DriverManager.setLoginTimeout(60);
        return DriverManager.getConnection(url, userName, password);
    }

    public static String getImportUnit(String erpNumber)
            throws Exception
    {
        String importUnit = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        Connection conn = null;
        conn = DBUtil.connect(FyConfig.getERP_DB_CONFIG());
        try
        {
            pst = conn.prepareStatement(" SELECT oa_Status FROM  apps.FYG_6_INV_DELV_HEADER f   WHERE  f.req_num=?");
            pst.setString(1, erpNumber);
            rs = pst.executeQuery();
            while (rs.next()) {
                importUnit = rs.getString(1);
            }
        }
        finally
        {
            if (rs != null) {
                rs.close();
            }
            if (pst != null) {
                pst.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        return importUnit;
    }
}
